package com.cisystem.system.service;

import com.cisystem.common.utils.MailUtil;
import com.cisystem.common.utils.StringUtils;
import com.cisystem.common.utils.spring.SpringUtils;
import com.cisystem.system.domain.EmailDomain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.HashMap;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;


/**
 * 类描述： 发邮件功能
 *
 * @author nsk
 */
@Service
public class SendEmailService {
    private static final Logger log = LoggerFactory.getLogger(SendEmailService.class);

    @Value("${spring.mail.defaultPoster}")
    private String defaultPoster;

    @Value("${spring.mail.username}")
    private String fromAddress;

    @Value("${spring.mail.nickname}")
    private String nickname;

    @Resource
    JavaMailSenderImpl mailSender;

    private Queue<EmailDomain> messageList = new ConcurrentLinkedQueue<>();

    /**
     * 方法描述: 异步发送邮件
     *
     * @param title   邮件名称 可以为null 默认为蜗牛会发光消息
     * @param contentArray 邮件内容 {内容title，名称，第一段内容，第二段内容}
     * @param sendTo  发送给谁
     */
    @Async
    public void sendAssignEmail(String title, String[] contentArray, String sendTo) {
        String content = "";
        try {
            content = MailUtil.buildContent(contentArray);
            //创建一个复杂的邮件
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            //组装
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            if (StringUtils.isEmpty(title)) {
                title = "消息提醒";
            }
            helper.setSubject(title);
            //可以开启html
            helper.setText(content, true);
            if (StringUtils.isEmpty(sendTo) || !sendTo.matches("[0-9a-zA-Z]{1,20}@[0-9a-zA-Z.]{1,20}")) {
                log.error("发送邮件接收人不合法：{},标题：{}内容：{}", sendTo, title, content);
                return;
            }
            helper.setTo(sendTo);
            helper.setFrom(fromAddress, nickname);
            EmailDomain emailDomain = new EmailDomain(mimeMessage, new Date(), sendTo, content);
            messageList.offer(emailDomain);
        } catch (Exception e) {
            log.error("组装发送邮件失败!收件人：{},标题：{}内容：{}", sendTo, title, content, e);
        }
    }
    /**
     * 方法描述: 异步发送邮件
     *
     * @param title   邮件名称 可以为null 默认为蜗牛会发光消息
     * @param content 邮件内容
     * @param sendTo  发送给谁
     */
    @Async
    public void sendEmail(String title, String content, String sendTo) {
        try {
            //创建一个复杂的邮件
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            //组装
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            if (StringUtils.isEmpty(title)) {
                title = "消息提醒";
            }
            helper.setSubject(title);
            //可以开启html
            String contentHtml = "<h3 style='color:red;'>" + content + "</h3>";
            helper.setText(contentHtml, true);
            if (StringUtils.isEmpty(sendTo) || !sendTo.matches("[0-9a-zA-Z]{1,20}@[0-9a-zA-Z.]{1,20}")) {
                log.error("发送邮件接收人不合法：{},标题：{}内容：{}", sendTo, title, content);
                return;
            }
            helper.setTo(sendTo);
            helper.setFrom(fromAddress, nickname);
            EmailDomain emailDomain = new EmailDomain(mimeMessage, new Date(), sendTo, content);
            messageList.offer(emailDomain);
        } catch (Exception e) {
            log.error("组装发送邮件失败!收件人：{},标题：{}内容：{}", sendTo, title, content, e);
        }
    }

    @PostConstruct
    private void sendTimerMessage() {
        log.info("开启送邮件线程。。。");
        new Thread(() -> {
            while (true) {
                if (!messageList.isEmpty()) {
                    try {
                        EmailDomain emailDomain = messageList.poll();
                        if (null != emailDomain) {
                            MimeMessage mimeMessage = emailDomain.getMimeMessage();
                            mailSender.send(mimeMessage);
                            log.info("给" + emailDomain.getSendTo() + "发送了：" + emailDomain.getContent());
                        }
                        Thread.sleep(3000);
                    } catch (Exception e) {
                        log.error("发送邮件失败", e);
                    }
                }
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    public void sendToMe(String title, String content) {
        SendEmailService aopProxy = SpringUtils.getAopProxy(this);
        aopProxy.sendEmail("[Party]" + (StringUtils.isEmpty(title) ? "" : ":" + title), content, defaultPoster);
    }

}
